import 'package:flutter/material.dart';

class Input extends StatefulWidget {
  final String placeholder;
  final TextEditingController textController;
  final bool isPassword;
  final String normalErrorText;
  final RegExp reg;
  final int maxLines;
  final List<int> errorList; // 错误列表
  final int index; // 索引
  final ValueChanged<List<int>> setErrorList; // 更新输入错误列表

  Input({
    Key key,
    this.placeholder,
    this.textController,
    this.isPassword,
    this.normalErrorText,
    this.reg,
    this.maxLines = 18,
    @required this.errorList,
    @required this.index,
    @required this.setErrorList,
  }) : super(key: key);

  @override
  _InputState createState() => _InputState();
}

class _InputState extends State<Input> {
  String errorText = '';
  bool showPassword = false;
  Color eyeColor = Colors.grey;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 30, right: 15),
      padding: EdgeInsets.fromLTRB(0, 0, 5, 0),
      child: TextField(
        maxLength: widget.maxLines,
        controller: widget.textController,
        decoration: InputDecoration(
            icon: widget.isPassword ? Icon(Icons.lock) : Icon(Icons.person),
            hintText: widget.placeholder,
            errorText: errorText == '' ? null : errorText,
            suffixIcon: widget.isPassword
                ? IconButton(
                    icon: Icon(
                      Icons.remove_red_eye,
                      color: eyeColor,
                    ),
                    onPressed: () {
                      setState(() {
                        // 如果之前的showPassword为真，说明点击一下需要隐藏密码，所以颜色变为灰色
                        eyeColor = showPassword ? Colors.grey : Colors.blue;
                        showPassword = !showPassword;
                      });
                    },
                  )
                : null),
        obscureText: widget.isPassword && !showPassword,
        onChanged: (text) {
          if (text == '') {
            setState(() {
              errorText = '输入不能为空';
            });
            changeErrorList(true);
            return;
          }
          if (!widget.reg.hasMatch(text)) {
            // 验证不通过
            setState(() {
              errorText = widget.normalErrorText;
            });
            changeErrorList(true);
            return;
          }
          setState(() {
            errorText = '';
          });
          changeErrorList(false);
        },
      ),
    );
  }

  void changeErrorList(bool isAdd) {
    List<int> list = List.from(widget.errorList);
    if (isAdd) {
      if (list.indexOf(widget.index) == -1) {
        // 说明找不到该元素，应增加
        list.add(widget.index);
      }
    } else {
      if (list.indexOf(widget.index) != -1) {
        list.remove(widget.index);
      }
    }

    widget.setErrorList(list);
  }
}
